package util

import (
	"reflect"
)

// ==================
// util-abstract_collection: 基础collection实现
// ==================

type AbstractCollection[E any] struct {
	collection[E]
}

// NewAbstractCollection create NewAbstractCollection
func NewAbstractCollection[E any]() AbstractCollection[E] {
	absCollection := AbstractCollection[E]{}
	absCollection.collection = &absCollection
	return absCollection
}

// ToArray 转为切片
//
//	Parameters
//		objs []E切片
//		function E到T转换函数
//	Returns
//		[]T 切片
func ToArray[E, T any](objs []E, convert func(E) T) []T {
	array := make([]T, len(objs))
	for i, obj := range objs {
		array[i] = convert(obj)
	}
	return array
}

// IsEmpty 判断是否为空
//
//	Returns
//		bool 是否为空
func (receiver *AbstractCollection[E]) IsEmpty() bool {
	return receiver.Size() == 0
}

// Contains 判断是否为空
//
//	Returns
//		bool 是否为空
func (receiver *AbstractCollection[E]) Contains(o E) bool {
	it := receiver.Iterator()
	if o == nil {
		for it.HasNext() {
			if it.Next() == nil {
				return true
			}
		}
	} else {
		for it.HasNext() {
			val := it.Next()
			if &val == &o || reflect.DeepEqual(o, val) {
				return true
			}
		}
	}
	return false
}

// ToSlice
//
//	Returns
//		[]interface{} 切片
func (receiver *AbstractCollection[E]) ToSlice() []interface{} {
	objs := make([]interface{}, receiver.Size())
	it := receiver.Iterator()
	l := len(objs)
	for i := 0; i < l; i++ {
		if !it.HasNext() {
			return make([]interface{}, 0)
		} else {
			objs[i] = it.Next()
		}
	}
	return objs
}

// ToGenericSlice
//
//	Returns
//		[]E 切片
func (receiver *AbstractCollection[E]) ToGenericSlice() []E {
	objs := make([]E, receiver.Size())
	it := receiver.Iterator()
	l := receiver.Size()
	for i := 0; i < l; i++ {
		if !it.HasNext() {
			return make([]E, 0)
		} else {
			objs[i] = it.Next()
		}
	}
	return objs
}
